package com.zst.dollars.handler.server;

import com.zst.dollars.entity.signin.ClientSignInAnnounceMessage;
import com.zst.dollars.entity.signin.ClientSignInRequestMessage;
import com.zst.dollars.entity.signin.ServerSignInResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 用于响应客户端注册的handler
 */
public class ClientSignInHandler extends SimpleChannelInboundHandler<ClientSignInRequestMessage> {
    private ConcurrentHashMap<String, String> clientTokenUsernameMap;
    private ChannelGroup channelGroup;

    public ClientSignInHandler(ConcurrentHashMap<String, String> map, ChannelGroup channelGroup){
        this.clientTokenUsernameMap = map;
        this.channelGroup = channelGroup;
    }

    /**
     * 处理客户端注册事件，步骤如下
     * 1，保存客户端token和username
     * 2，广播新客户端进入的消息
     * 3，回复客户端注册成功
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ClientSignInRequestMessage msg) throws Exception {
        //保存token和用户名的关联关系
        String clientToken = msg.getClientToken();
        if(!clientTokenUsernameMap.containsKey(clientToken)){

        }
        clientTokenUsernameMap.put(clientToken, msg.getUsername());

        //广播新客户端进入的消息
        ClientSignInAnnounceMessage signInAnnounceMessage = new ClientSignInAnnounceMessage(msg.getUsername());
        channelGroup.writeAndFlush(signInAnnounceMessage);

        //回复客户端注册成功
        ServerSignInResponseMessage signInResponseMessage = new ServerSignInResponseMessage();
        ctx.writeAndFlush(signInResponseMessage);
    }
}
